package com.xiaojimao.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xaiojimao.gr_common.CommonEnum.BizCommonEnum;
import com.xaiojimao.gr_common.CommonPojo.OpenUser;
import com.xiaojimao.Feign.UserFeignService;
import com.xaiojimao.gr_common.dto.Result;
import com.xiaojimao.Mapper.ArticleCommentMapper;
import com.xiaojimao.Pojo.Article;
import com.xiaojimao.Pojo.ArticleComment;
import com.xiaojimao.Service.ArticleCommentService;
import com.xiaojimao.Service.ArticleService;
import com.xiaojimao.Service.SensitiveWordsService;
import com.xiaojimao.Utils.ArticleConstant;
import com.xiaojimao.Utils.ThreadLocalUtil;
import com.xiaojimao.Vo.SensitiveVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {

    @Autowired
    SensitiveWordsService sensitiveWordsService;

    @Autowired
    ArticleService articleService;

    @Autowired
    UserFeignService userFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public Result comment(ArticleComment comment) {
        // 检查该文章是否可评论
        Article article = (Article) articleService.getByArticleId(comment.getArticleId()).getData();
        if (article != null) {
            // 根据用户id获得用户实体
            OpenUser user = userFeignService.getUserById(ThreadLocalUtil.getUserId());
            if (user == null) {
                return Result.fail(BizCommonEnum.USER_NOT_EXITS_ERROR);
            }

            // 用户id
            comment.setUserId(user.getId());
            // 用户头像
            comment.setUserAvatar(user.getAvatar());
            // 用户昵称
            comment.setUserNickName(user.getNickName());
            // 设置状态
            comment.setStatus(2);

            save(comment);

            // 检查评论内容是否敏感
            rabbitTemplate.convertAndSend("article.exchange", ArticleConstant.ROUTING_KEY_REVIEW_COMMENT, JSON.toJSONString(comment));

            return Result.success();
        } else {
            return Result.fail(BizCommonEnum.ARTICLE_STATUS_ERROR);
        }

    }
}
